package com.example.asyncwrite.kafka;

import com.alibaba.fastjson2.JSON;
import com.example.asyncwrite.mapper.OrderItemMapper;
import com.example.asyncwrite.mapper.OrderItemMapper2;
import com.example.asyncwrite.mapper.OrderMapper;
import com.example.asyncwrite.mapper.OrderMapper2;
import com.example.asyncwrite.model.Order2;
import com.example.asyncwrite.model.OrderDTO;
import com.example.asyncwrite.model.OrderItem;
import com.example.asyncwrite.model.OrderItem2;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.TopicBuilder;

@Configuration
@Slf4j
public class WriteConsumer {

    @Bean
    public NewTopic topic() {
        return TopicBuilder.name("order_new")
                .partitions(3)
                .replicas(1)
                .build();
    }

    @Autowired
    private OrderMapper2 orderMapper222;

    @Autowired
    private OrderItemMapper2 itemMapper222;

    @KafkaListener(id = "orderWew", topics = "order_new")
    public void orderWew(String in) {
        OrderDTO orderDTO = JSON.parseObject(in, OrderDTO.class);
        log.info(orderDTO.toString());
        Order2 order2 = new Order2();
        BeanUtils.copyProperties(orderDTO.getOrder(), order2);
        orderMapper222.insert(order2);
        for (OrderItem item : orderDTO.getItems()) {
            OrderItem2 orderItem2 = new OrderItem2();
            BeanUtils.copyProperties(item, orderItem2);
            itemMapper222.insert(orderItem2);
        }

    }


}
